/*
 * Copyright 2008 Andrej Herich
 * 
 * http://azetclient.yw.sk/
 * http://azetclient.googlecode.com/
 * 
 * This file is part of AzetClient.
 * 
 * AzetClient is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * AzetClient is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with AzetClient.  If not, see <http://www.gnu.org/licenses/>.
 */

package sk.yw.azetclient.gui;

import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import org.apache.log4j.Logger;
import sk.yw.azetclient.Main;
import sk.yw.azetclient.azet.AzetMessageBean;
import sk.yw.azetclient.model.Buddy;
import sk.yw.azetclient.model.Message;
import sk.yw.azetclient.model.MessageBean;
import sk.yw.azetclient.model.MessageThread;
import sk.yw.azetclient.model.MessageThreadEvent;
import sk.yw.azetclient.model.MessageThreadListener;

/**
 *
 * @author  error216
 */
public class ConversationPanel extends javax.swing.JPanel
        implements MessageThreadListener {
    
    private static final long serialVersionUID = 2565874029l;
    
    private static final Logger logger =
            Logger.getLogger(ConversationPanel.class);
    
    private static final Style DEFAULT_STYLE = StyleContext
            .getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    
    private static final DateFormat MESSAGE_DATE_FORMAT =
            new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    private static final String MESSAGE_NULL_DATE = "??.??.?? ??:??:??";
    
    private ConversationFrame frame;
    private Buddy user;
    private Buddy buddy;
    private MessageThread thread;
    private StyledDocument conversationDocument;
    private StyledDocument inputDocument;
    private List<Integer> offsets = new ArrayList<Integer>();
    
    /** Creates new form MessagThreadPanel */
    public ConversationPanel(ConversationFrame frame, Buddy user, Buddy buddy,
            MessageThread thread) {
        if (frame == null)
            throw new IllegalArgumentException("Null pointer in frame");
        if (user == null)
            throw new IllegalArgumentException("Null pointer in user");
        if (buddy == null)
            throw new IllegalArgumentException("Null pointer in buddy");
        // Generally this should be checked, but it's commented out until
        // proper buddy info retrieving API will be developed.
        //if (buddy.getId() == 0)
        //    throw new IllegalArgumentException("Buddy id is 0");
        if (thread == null)
            throw new IllegalArgumentException("Null pointer in thread");
        
        this.frame = frame;
        this.user = user;
        this.buddy = buddy;
        this.thread = thread;
        
        initComponents();
        
        conversationDocument = conversationTextPane.getStyledDocument();
        Style userMessageStyle =
                conversationDocument.addStyle("userMessage", DEFAULT_STYLE);
        StyleConstants.setForeground(userMessageStyle, Color.GRAY);
        
        inputDocument = inputTextPane.getStyledDocument();
        
        synchronized (thread) {
            if (thread.getLastMessage() != null) {
                if (user.equals(thread.getLastMessage().getReceiver())) {
                    Main.getMainFrame().getConversationFocusQueue().add(this);
                }
            
                if (user.equals(thread.getLastMessage().getSender())) {
                    inputTextPane.setEnabled(false);
                    setWaitingForReplyText();
                }
            }
        
            synchronized (conversationDocument) {
                thread.addMessageThreadListener(this);
            
                for (Message message : thread.getMessages()) {
                    addMessage(message);
                }
            }
        }
    }
    
    public void dispose() {
        thread.removeMessageThreadListener(this);
        Main.getMainFrame().getConversationFocusQueue().remove(this);
    }
    
    private void setWaitingForReplyText() {
        try {
            inputDocument.insertString(0,
                    Main.getText("conversationPanel.waitingForReply"),
                    DEFAULT_STYLE);
        } catch (BadLocationException ex) {
            logger.error("Unable to insert 'waiting for reply' message to input text pane", ex);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        conversationTextPane = new javax.swing.JTextPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        inputTextPane = new javax.swing.JTextPane();

        jSplitPane1.setDividerLocation(230);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        conversationTextPane.setEditable(false);
        jScrollPane1.setViewportView(conversationTextPane);

        jSplitPane1.setTopComponent(jScrollPane1);

        inputTextPane.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputTextPaneKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(inputTextPane);

        jSplitPane1.setRightComponent(jScrollPane2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void inputTextPaneKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputTextPaneKeyPressed
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
            inputTextPane.setEnabled(false);
            
            final MessageBean bean;
            if (getThread().isEmpty()) {
                bean = new AzetMessageBean();
                bean.setSender(user);
                bean.setReceiver(buddy);
            } else {
                bean = getThread().getLastMessage().createReplyBean();
                if (bean.getReceiver().getId() == 0) {
                    bean.setReceiver(buddy);
                }
            }
            
            try {
                bean.setContent(
                        inputDocument.getText(0, inputDocument.getLength()));
            } catch (BadLocationException ex) {
                logger.error("Unable to get message text from input text pane.", ex);
            }
            
            try {
                inputDocument.remove(0, inputDocument.getLength());
            } catch (BadLocationException ex) {
                logger.error("Unable to remove message text from input text pane.", ex);
            }
            
            setWaitingForReplyText();
            
            bean.setSendTime(Calendar.getInstance().getTime());
            
            final Message message;
            synchronized (getThread()) {
                getThread().addMessage(bean);
                message = getThread().getLastMessage();
            
                if (getThread().getMessages().size() == 1) {
                    frame.setSelectedConversationName(getThread().getName());
                }
            }
            
            (new Thread() {
                @Override
                public void run() {
                    Main.getMainFrame().getConversationFocusQueue()
                            .requestNextFocus();
                    Main.getMainFrame().sendMessage(message);
                }
            }).start();
        }
    }//GEN-LAST:event_inputTextPaneKeyPressed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane conversationTextPane;
    private javax.swing.JTextPane inputTextPane;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration//GEN-END:variables
    
    private void addMessage(Message message) {
        StringBuilder builder = new StringBuilder();
        builder.append('(');
        Date sendTime = message.getSendTime();
        if (sendTime == null) {
            builder.append(MESSAGE_NULL_DATE);
        } else {
            builder.append(MESSAGE_DATE_FORMAT.format(sendTime));
        }
        builder.append(')');
        builder.append(' ');
        builder.append(message.getContent());
        builder.append('\n');
        
        Style style;
        if (user.equals(message.getSender())) {
            style = conversationDocument.getStyle("userMessage");
        } else {
            style = DEFAULT_STYLE;
        }
        
        offsets.add(conversationDocument.getLength());
        
        try {
            conversationDocument.insertString(
                    conversationDocument.getLength(),
                    builder.toString(),
                    style);
        } catch (BadLocationException ex) {
            logger.error("Unable to add message to conversation text pane.", ex);
        }
        
        if (user.equals(message.getReceiver())) {
            try {
                inputDocument.remove(0, inputDocument.getLength());
            } catch (BadLocationException ex) {
                logger.error("Unable to remove 'waiting for reply' message.", ex);
            }
            inputTextPane.setEnabled(true);
        }
        
        conversationTextPane.scrollRectToVisible(new Rectangle(new Point(0, 
                conversationTextPane.getHeight())));
    }
    
    private void removeLastMessage() throws BadLocationException {
        int lastMessageOffset = offsets.get(offsets.size() - 1);
        conversationDocument.remove(lastMessageOffset,
                conversationDocument.getLength() - lastMessageOffset);
    }

    public void messageAdded(final MessageThreadEvent e) {
        if (user.equals(e.getMessage().getReceiver())) {
            Main.getMainFrame().getConversationFocusQueue().add(this);
        } else {
            Main.getMainFrame().getConversationFocusQueue().remove(this);
        }
        
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                synchronized (conversationDocument) {
                    addMessage(e.getMessage());
                }
            }
        });
    }

    public void messageChanged(final MessageThreadEvent e) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                try {
                    removeLastMessage();
                    addMessage(e.getMessage());
                } catch (BadLocationException ex) {
                    logger.error("Unable to remove message from text pane.", ex);
                }
            }
        });
    }

    public void messageRemoved(MessageThreadEvent e) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                try {
                    removeLastMessage();
                } catch (BadLocationException ex) {
                    logger.error("Unable to remove message from text pane.", ex);
                }
            }
        });
    }
    
    public void requestFocusOnInputTextPane() {
        inputTextPane.requestFocus();
    }
    
    public void requestFocusInWindowOnInputTextPane() {
        inputTextPane.requestFocusInWindow();
    }

    public ConversationFrame getFrame() {
        return frame;
    }

    public MessageThread getThread() {
        return thread;
    }
}
